<template>
  <main>
    <van-field 
      v-model="phone" 
      maxlength="11"
      type="digit" 
      clearable
      label="手机号" 
      placeholder="请输入要找回密码的手机号"/>
    <van-field
      v-model="captcha"
      type="digit"
      maxlength="4"
      center
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
    >
      <template #button>
        <van-button 
          size="small" 
          :disabled="disabled" 
          class="default-btn"
          @click="sendSms">
          {{ !timer ? sendText : count + '秒后重新发送'}}
        </van-button>
      </template>
    </van-field>
    <van-button 
      class="default-btn btn"
      @click="onSubmit"
      block>
      确认
    </van-button>
  </main>
</template>

<script>
import { Dialog, Toast } from 'vant';
import { mapActions } from 'vuex';
import * as Api from 'api'

export default {
  name: 'home-view',
  data() {
    return {
      phone: '',
      captcha: '',
      timer: null,
      smsLoading: false,
      count: 60,
      sendText: '发送验证码',
    }
  },
  computed: {
    disabled() {
      if (this.timer || this.smsLoading) {
        return true
      } 
      return false
    }
  },
  created() {
    this.$emit('showTabMenu', false);
  },
  methods: {
    ...mapActions([
      'UnSetPassword',
      'SetUserInfo'
    ]),
    // 发送短信
    sendSms() {
      if (this.phone.length<11) {
        Toast('请输入正确的手机号！')
        return
      }
      this.smsLoading = true
      this.sendText = '发送中...'
      Api.SendSms({phone: this.phone}).then(res => {
        Toast(res.message)
        this.isSend = true
        this.smsLoading = false
        this.intervalCount()
      }).catch(() => {
        this.smsLoading = false
      })
    },
    // 倒计时
    intervalCount() {
      this.count = 60
      this.timer = setInterval(() => {
        this.count --
        if (this.count <= 0) {
          this.isSend = false
          this.sendText = '发送验证码',
          clearInterval(this.timer)
        }
      }, 1000)
    },
    onSubmit() {
      if (this.phone.length < 11) {
        Toast('请输入正确的手机号!')
        return
      }
      if (!this.captcha) {
        Toast('验证码不能为空!')
        return
      }
      let params = {
        phone: this.phone,
        captcha: this.captcha
      }
      Api.CheckCaptcha(params).then(res => {
        this.UnSetPassword(true)
        this.SetUserInfo(params)
        this.$router.push({name: 'SetPassword'})
      })
    },
  },
  destroyed() {
    clearInterval(this.timer)
  }
}
</script>

<style scoped lang="less">
main{
  padding-top: 40px;
}
.btn{
  margin: 60px auto;
  width: 90%;
}
</style>
